package com.xizi.forum.controller;

import com.xizi.forum.common.AppResult;
import com.xizi.forum.common.Constants;
import com.xizi.forum.common.ResultCode;
import com.xizi.forum.exception.ApplicationException;
import com.xizi.forum.model.UserInfo;
import com.xizi.forum.service.IUserService;
import com.xizi.forum.utils.StringUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;



//用户模块
@RequestMapping("/user")
@RestController
@Slf4j
// API 描述信息
@Tag(name = "用户管理", description = "论坛用户相关操作")
public class UserController {
    @Autowired
    private IUserService userService;

    /**
     * 用户注册
     *
     * @param username       用户名（唯一）
     * @param nickname       昵称
     * @param password       密码
     * @param passwordRepeat 重复密码
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST, produces = "application/json")
    @Operation(summary = "注册新用户", description = "返回注册新用户是否成功")
    public AppResult register(@RequestParam String username,
                              @RequestParam String nickname,
                              @RequestParam String password,
                              @RequestParam String passwordRepeat) {
        log.info("username = " + username + ",nickname = " + nickname +
                ",password = " + password + ",passwordRepeat = " + passwordRepeat);
        // 1.参数校验
        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(nickname) || StringUtil.isEmpty(password) || StringUtil.isEmpty(passwordRepeat)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        userService.register(username, nickname, password, passwordRepeat);
        return AppResult.success();
    }

    /**
     * 用户登入
     *
     * @param username 用户名（唯一）
     * @param password 密码
     * @param session
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json")
    public AppResult login(String username, String password, HttpSession session) {
        log.info("username = " + username + ",password = " + password);
        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        userService.login(session, username, password);
        return AppResult.success();
    }

    /**
     * 用户退出登入
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET, produces = "application/json")
    public AppResult logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            log.info("用户未登入！");
            session.invalidate();
        }
        System.out.println("用户退出成功！");
        return AppResult.success();
    }

    /**
     * 查询用户信息
     *
     * @param request
     * @param id      用户id
     * @return
     */
    @RequestMapping(value = "/info", method = RequestMethod.GET, produces = "application/json")
    public AppResult info(HttpServletRequest request, Long id) {
        log.info("request: {}", request);
        UserInfo userInfo = null;
        log.info("id : {}", id);

        if (id != null) {//1.通过id查询用户信息
            userInfo = userService.selectUserInfoById(id);
        } else {// 2.查询当前登入用户的信息
            HttpSession session = request.getSession(false);
            if (session != null) {
                userInfo = (UserInfo) session.getAttribute(Constants.USERINFO);
            } else {
                log.error(ResultCode.FAILED_NOT_LOGIN.toString() + "拦截器出错了！");
                throw new ApplicationException(ResultCode.FAILED_NOT_LOGIN);
            }
        }
        log.info("session: {}", userInfo);
        return AppResult.success(userInfo);
    }

    /**
     * 修改密码
     *
     * @param request
     * @param oldPassword    老密码
     * @param newPassword    新密码
     * @param passwordRepeat 确认新密码
     * @return
     */
    @RequestMapping(value = "modifyPwd", method = RequestMethod.POST, produces = "application/json")
    public AppResult modifyPwd(HttpServletRequest request, String oldPassword, String newPassword, String passwordRepeat) {
        HttpSession session = request.getSession(false);
        UserInfo userInfo = (UserInfo) session.getAttribute(Constants.USERINFO);
        Long id = userInfo.getId();
        log.info("id = " + id + ",oldPassword = " + oldPassword + ",newPassword = " + newPassword + ",passwordRepeat = " + passwordRepeat);
        //1.参数校验
        if (id == null || StringUtil.isEmpty(oldPassword) || StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(passwordRepeat)) {
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //2.校验 新密码 与 确认新密码 是否相同
        if (!newPassword.equals(passwordRepeat)) {
            log.info(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            throw new ApplicationException(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        userService.updatePassword(id, oldPassword, newPassword);

        return AppResult.success();
    }

    /**
     * 修改用户信息
     *
     * @param request
     * @param userInfo
     * @return
     */
    @PostMapping("/modifyInfo")//String username,String nickname,Byte gender, String email,String phoneNum,String remark
    public AppResult modifyInfo(HttpServletRequest request, UserInfo userInfo) {
        //1.校验用户是否登入
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute(Constants.USERINFO) == null) {
            log.info(ResultCode.FAILED_NOT_LOGIN.toString());
            throw new ApplicationException(ResultCode.FAILED_NOT_LOGIN);
        }
        //2.通过session 获取当前 登入用户
        UserInfo userInfoCur = (UserInfo) session.getAttribute(Constants.USERINFO);
        userInfo.setId(userInfoCur.getId());
        log.info("userInfoCur : {}", userInfoCur);

        //3.进行修改
        UserInfo retUserInfo = userService.updateUserInfo(userInfo);
        log.info("retUserInfo: {}", retUserInfo);
        session.setAttribute(Constants.USERINFO, retUserInfo);

        return AppResult.success(retUserInfo);
    }

    /**
     *  上传头像
     * @param avatar
     * @param request
     * @return
     */
    @PostMapping("/upload-avatar")
    public AppResult<UserInfo> uploadAvatar(@RequestParam("avatar") MultipartFile avatar, HttpServletRequest request) {
        // 获取当前用户信息
        HttpSession session = request.getSession(false);
        UserInfo userInfoCur = (UserInfo) session.getAttribute(Constants.USERINFO);
        if (userInfoCur == null) {
            return AppResult.fail(ResultCode.FAILED_NOT_LOGIN);
        }

        if (avatar.isEmpty()) {
            return AppResult.fail(ResultCode.FAILED_NO_AVATAR);
        }

        //修改session中存储信息
        String avatarUrl = userService.saveAvatar(userInfoCur.getId(),avatar);
        userInfoCur.setAvatarUrl(avatarUrl);
        session.setAttribute(Constants.USERINFO, userInfoCur);


        UserInfo retUserInfo = new UserInfo();
        retUserInfo.setId(userInfoCur.getId());
        retUserInfo.setAvatarUrl(avatarUrl);

        return AppResult.success(retUserInfo);
    }

    /**
     * 删除用户 （逻辑删除）
     * @param request
     * @return
     */
    @RequestMapping("/delete")
    public AppResult delete(HttpServletRequest request){
        HttpSession session = request.getSession(false);

        if(session == null || session.getAttribute(Constants.USERINFO) == null){
            log.info(ResultCode.FAILED_NOT_LOGIN.toString());
            throw new ApplicationException(ResultCode.FAILED_NOT_LOGIN);
        }

        UserInfo userInfo = (UserInfo) session.getAttribute(Constants.USERINFO);
        Boolean check = userService.deleteUserInfo(userInfo.getId());
        return AppResult.success();
    }

}
